/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.extremecomponents.util;

import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.tag.TableItemsTag;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author Eccn-sshwsfc
 * XML Utils
 */
public class XmlUtils {

    public static void sendTableData(HttpServletResponse response, HttpServletRequest request, TableModel model) throws Exception {
        Document doc = newDocument();
        Element root = addRootElement(doc, TableItemsTag.AJAX_NODE_TAG);
        root.setAttribute("id", model.getTableHandler().getTable().getTableId());
        
        appendText(root, doc, model.getViewData().toString());

        sendDOMDocument(response, doc);
    }


    private static Element addRootElement(Document doc, String rootTagName) {
        Element root = doc.createElement(rootTagName);
        doc.appendChild(root);
        return root;
    }

    private static void sendDOMDocument(HttpServletResponse response, Document doc) {
        try {
            response.setContentType("text/xml");
            
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Pragma", "no-cache");

            Transformer transformer = TransformerFactory.newInstance().newTransformer();

            transformer.transform(new DOMSource(doc), new StreamResult(response.getOutputStream()));
            response.flushBuffer();
            
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private static Document newDocument() {
        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
    }

    private static void appendText(Element zoneNode, Document doc, String content) {
        zoneNode.appendChild(doc.createCDATASection(content));
    }

    public static void handleError(HttpServletResponse response, Throwable exception) {
        Document doc = newDocument();

        Element root = addRootElement(doc, "exception");
        root.setAttribute("type", exception.getClass().getName());
        StringWriter sw = new StringWriter();
        exception.printStackTrace(new PrintWriter(sw));
        appendText(root, doc, sw.toString().replace('\r', ' '));

        sendDOMDocument(response, doc);

    }
}
